package com.miyu.client1.service.book.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.poi.ss.formula.functions.T;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;

public class TaskCallable implements Callable<JSONArray> {
    JSONArray data = new JSONArray();
    List<Map<String,Object>> rs = new ArrayList<>();
    Map<String,Object> mp= new HashMap<>();
    JSONObject jo = new JSONObject();
    String bookCode="";
    String chartNum="";
    String chartInfo="";
    private int id;
    private List list;
    private int i=0;

    public TaskCallable(List t) {
        this.list = t;
    }

    @Override
    public JSONArray call() throws Exception {

        for (Object j : list) {
            mp.clear();
            JSONObject jo = JSONObject.parseObject(j.toString());
            chartInfo = jo.getString("h");
            bookCode=chartInfo.substring(chartInfo.indexOf("/"),chartInfo.lastIndexOf("/"));
            chartNum=chartInfo.substring(chartInfo.lastIndexOf("/")+1,chartInfo.length());

            jo.put("titleName",jo.getString("titleName"));
            jo.put("num",chartNum);
            jo.put("text",readText("ddxs",bookCode,chartNum));
            data.add(jo);
        }
        return data;
    }


    public String readText(String ddxs, String bookCode, String chapterCod) {
        String text="";
        try {
            Document document = Jsoup.connect("http://www.ddxs.com/" + bookCode + "/" + chapterCod + ".html").get();
            Element amain = document.getElementById("amain");
            Elements chapterName = amain.getElementsByTag("h1");
            String p = document.select("#contents").html();
             text = p.replace("<script>show_htm2();</script> ", "")
                    .replace("/n", "")
                    .replace("<script>show_htm3();</script>", "")
                    .replace("<p>", "")
                    .replace("</p>", "");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        return text;
    }
}
